
import QtQuick 2.14
import QtQuick.Controls 2.14
import Review 1.0   // MeasurementManager 已注册

ApplicationWindow {
    visible: true
    width: 800
    height: 800

    MeasurementManager { id: manager }

    property var rawPoints: []
    property var smoothPoints: []
    property double areaValue: 0
    property int hoveredIndex: -1     // 当前鼠标悬停点
    property int draggingIndex: -1    // 当前拖拽点
    property bool areaSelected: false // 👈 是否选中面积
    property bool editing: true   // 👉 是否允许打点

    Canvas {
        id: canvas
        anchors.fill: parent
        // 根据是否在编辑模式下设置鼠标形状
       // cursorShape: editing ? Qt.CrossCursor : Qt.ArrowCursor
        onPaint: {
            var ctx = getContext("2d")
            ctx.clearRect(0,0,width,height)

            // 绘制拟合曲线
            if (smoothPoints.length > 1) {
                ctx.beginPath()
                ctx.moveTo(smoothPoints[0].x, smoothPoints[0].y)
                for (var i=1; i<smoothPoints.length; i++)
                    ctx.lineTo(smoothPoints[i].x, smoothPoints[i].y)
                ctx.closePath()

                if (areaSelected) {   // 👈 面积模式下填充高亮
                    ctx.fillStyle = "rgba(255,165,0,0.3)" // 半透明橙色
                    ctx.fill()
                }

                ctx.strokeStyle = "orange"
                ctx.lineWidth = 2
                ctx.stroke()
            }

            // 遍历 rawPoints 数组中的所有点
            for (var i=0; i<rawPoints.length; i++) {
                ctx.beginPath()   // 开始一条新的绘图路径
                ctx.arc(
                    rawPoints[i].x, rawPoints[i].y,   // 点的坐标
                    (i === hoveredIndex ? 6 : 4),     // 半径：悬停点大一点（6），普通点小一点（4）
                    0, Math.PI*2                      // 绘制完整的圆
                )
                ctx.fillStyle = (i === hoveredIndex ? "yellow" : "red") // 悬停点黄色，其他点红色
                ctx.fill()         // 填充圆形
            }
        }

        MouseArea {
            anchors.fill: parent
            hoverEnabled: true
            cursorShape: editing ? Qt.CrossCursor : Qt.ArrowCursor

            // 🟩 防抖计时器（避免连续加点）
            property double lastAddTime: 0

            onClicked: {
                // 🟨 仅编辑状态下允许点击打点
                if (editing && hoveredIndex === -1) {
                    rawPoints.push({x: mouse.x, y: mouse.y})
                 //   smoothPoints = manager.smoothCurve(rawPoints)
                  //  areaValue = manager.polygonArea(smoothPoints)
                    canvas.requestPaint()
                }
            }

            onPositionChanged: {
                // 拖拽中（编辑或非编辑状态都支持）
//                if (draggingIndex >= 0) {
//                    rawPoints[draggingIndex].x = mouse.x
//                    rawPoints[draggingIndex].y = mouse.y
//                    smoothPoints = manager.smoothCurve(rawPoints)
//                    areaValue = manager.polygonArea(smoothPoints)
//                    canvas.requestPaint()
//                    return
//                }

                // 🟨 非编辑状态下允许拖拽
                if (!editing && draggingIndex >= 0) {
                    rawPoints[draggingIndex].x = mouse.x
                    rawPoints[draggingIndex].y = mouse.y
                    smoothPoints = manager.smoothCurve(rawPoints)
                    areaValue = manager.polygonArea(smoothPoints)
                    canvas.requestPaint()
                    return
                }

                // 🟨 编辑状态下允许拖拽
                if (editing && draggingIndex >= 0) {
                    rawPoints[draggingIndex].x = mouse.x
                    rawPoints[draggingIndex].y = mouse.y
                //    smoothPoints = manager.smoothCurve(rawPoints)
                  //  areaValue = manager.polygonArea(smoothPoints)
                    canvas.requestPaint()
                    return
                }

                // 检查鼠标是否靠近现有点
                hoveredIndex = -1
                for (var i=0; i<rawPoints.length; i++) {
                    var dx = rawPoints[i].x - mouse.x
                    var dy = rawPoints[i].y - mouse.y
                    if (Math.sqrt(dx*dx + dy*dy) < 8) {
                        hoveredIndex = i
                        break
                    }
                }

                canvas.requestPaint()
            }

            // 🟨 修改：无论编辑与否都可拖拽已有点
            onPressed: {
                // 🟩 新增静态变量用于防抖（存储上次添加时间）
                if (typeof lastAddTime === "undefined")
                    lastAddTime = 0

                var now = Date.now()

                // 仅非编辑状态下考虑自动添加点
                if (!editing && hoveredIndex === -1 && smoothPoints.length > 1 && mouse.button === Qt.LeftButton) {
                    // 🟩 防抖检测：两次添加间隔必须 > 300ms
                    if (now - lastAddTime < 300)
                        return

                    var nearCurve = false
                    for (var j = 0; j < smoothPoints.length - 1; j++) {
                        var p1 = smoothPoints[j]
                        var p2 = smoothPoints[j + 1]
                        var dist = pointToSegmentDistance(mouse.x, mouse.y, p1.x, p1.y, p2.x, p2.y)
                        if (dist < 5) {
                            nearCurve = true
                            break
                        }
                    }

                    if (nearCurve) {
                        console.log("Add new point at", mouse.x, mouse.y)
                        rawPoints.push({ x: mouse.x, y: mouse.y })
                        // smoothPoints = manager.smoothCurve(rawPoints)
                        // areaValue = manager.polygonArea(smoothPoints)
                        canvas.requestPaint()

                        // 🟩 更新上次添加时间
                        lastAddTime = now
                        return
                    }
                }

                // 🟨 修改：无论编辑与否都可拖拽已有点
                if (hoveredIndex >= 0)
                    draggingIndex = hoveredIndex
            }


            onReleased: {
                draggingIndex = -1
            }

            // 🟩 工具函数：计算点到线段距离
            function pointToSegmentDistance(px, py, x1, y1, x2, y2) {
                var vx = x2 - x1
                var vy = y2 - y1
                var wx = px - x1
                var wy = py - y1
                var c1 = vx * wx + vy * wy
                if (c1 <= 0)
                    return Math.sqrt(wx*wx + wy*wy)
                var c2 = vx * vx + vy * vy
                if (c2 <= c1)
                    return Math.sqrt((px - x2)*(px - x2) + (py - y2)*(py - y2))
                var b = c1 / c2
                var bx = x1 + b * vx
                var by = y1 + b * vy
                var dx = px - bx
                var dy = py - by
                return Math.sqrt(dx*dx + dy*dy)
            }
        }

    }


    Row {
        anchors.bottom: parent.bottom
        anchors.horizontalCenter: parent.horizontalCenter
        spacing: 10

        Button {
            text: "完成"
            onClicked: {

                if (rawPoints.length > 2) {
                 //   smoothPoints = manager.smoothCurve(rawPoints)
                 //   areaValue = manager.polygonArea(smoothPoints)
                    smoothPoints = manager.smoothCurve(rawPoints)
                    areaValue = manager.area(smoothPoints)   // 👈 强制更新

                    editing = false   // 👉 禁止再打点
                    areaSelected = true
                    areaButton.checked = true
                    canvas.requestPaint()
                }
            }
        }

        // 面积按钮，支持选中/取消
        Button {
            id: areaButton
            text: "面积"
            checkable: true         // 👈 按钮可切换
            checked: areaSelected   // 同步状态
            onClicked: {
                if (!checked) {
                    // 👉 退出面积模式，保持现有图形
                    areaSelected = false
                } else {
                    // 👉 重新进入面积模式：清空旧数据，允许重新打点
                    rawPoints = []
                    smoothPoints = []
                    areaValue = 0
                    editing = true
                    areaSelected = true
                }
                canvas.requestPaint()
            }
        }

        Label {
            text: "面积: " + areaValue.toFixed(2)        // 👈 绑定到 areaValue
        }
    }
}

